package com.example.newsmanager.interceptor;

import com.example.newsmanager.common.Result;
import com.example.newsmanager.entity.User;
import com.example.newsmanager.exception.TokenEmptyException;
import com.example.newsmanager.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

public class JwtInterceptor implements HandlerInterceptor {

    private final RedisTemplate<String,Object> template;
    public JwtInterceptor(RedisTemplate<String, Object> template) {
        this.template = template;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        try {
            if (token == null || token.isEmpty()) {
                throw new TokenEmptyException("Token is empty");
            }
            String key = JwtUtil.parseJwt(token);
            User user = (User) template.opsForValue().get(key);
            // 将用户信息存储到request的属性中
            request.setAttribute("currentUser", user);
            return true;
        } catch (TokenEmptyException e) {
            throw e; // 抛出自定义的TokenEmptyException
        } catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
}
